#include <QtNetwork>
#include <server.h>
#include <QtGui>

ServerStation::ServerStation(int nPort, QWidget* pwgt) : QWidget(pwgt), nNextBlockSize(0)
{
	ptcpServer = new QTcpServer(this);
	if (!ptcpServer->listen(QHostAddress::Any, nPort))
	{
		QMessageBox::critical(0,"server error","unable to start server" + ptcpServer->errorString());
		ptcpServer->close();
		return;
	}
	connect(ptcpServer, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
	in_memo = new QTextEdit;
	in_memo->setReadOnly(true);
	
	//Расположение
	QVBoxLayout* sLayout = new QVBoxLayout;
	sLayout->addWidget(new QLabel("<H1>Server</H1>"));
	sLayout->addWidget(in_memo);
	setLayout(sLayout);
}

void ServerStation::slotNewConnection()
{
	QTcpSocket* pClientSocket = ptcpServer->nextPendingConnection();
	connect(pClientSocket, SIGNAL(disconnected()), pClientSocket, SLOT(deleteLater()));
	connect(pClientSocket, SIGNAL(readyRead()), this, SLOT(slotReadClient()));
	sendToClient(pClientSocket, "Соединение установлено");
}

void ServerStation::slotReadClient()
{
	QTcpSocket* pClientSocket = (QTcpSocket*)sender();
	QDataStream in(pClientSocket);
	in.setVersion(QDataStream::Qt_4_2);
	while(true)
	{
		if (!nNextBlockSize)
		{
			if (pClientSocket->bytesAvailable() < sizeof(quint16))
			{
				break;
			}
			in >> nNextBlockSize;
		}
		if (pClientSocket->bytesAvailable() < nNextBlockSize)
		{
			break;
		}
		QTime time;
		QString str;
		in >> time >> str;
		QString strMessage = time.toString() + " " + "Client sender-" + str;
		in_memo->append(strMessage);
		nNextBlockSize = 0;
		sendToClient(pClientSocket, "\"" + str + "\" - Доставлено");
	}
}

void ServerStation::sendToClient(QTcpSocket* pSocket, const QString& str)
{
	QByteArray	arrBlock;
	QDataStream	out(&arrBlock, QIODevice::WriteOnly);
	out.setVersion(QDataStream::Qt_4_2);
	out << quint16(0) << QTime::currentTime() << str;
	
	out.device()->seek(0);
	out << quint16(arrBlock.size() - sizeof(quint16));
	
	pSocket->write(arrBlock);
}
